package io.github.talelin.sleeve.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.talelin.sleeve.bo.FileBO;
import io.github.talelin.sleeve.common.exception.NotFoundException;
import io.github.talelin.sleeve.common.model.FileDO;
import io.github.talelin.sleeve.mapper.FileTestMapper;
import io.github.talelin.sleeve.module.file.FileConstant;
import io.github.talelin.sleeve.module.file.Uploader;
import io.github.talelin.sleeve.service.FileTestService;
import io.github.talelin.sleeve.vo.BannerVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
public class FileTestServiceImpl extends ServiceImpl<FileTestMapper, FileDO> implements FileTestService {
    @Resource
    private FileTestMapper fileTestMapper;
    @Autowired
    private Uploader uploader;
    @Value("${bld.file.domain}")
    private String domain;

    @Value("${bld.file.serve-path:assets/**}")
    private String servePath;
    @Override
    public List<List<String>> generateHead(String tableName) {
        List<List<String>> excelInfo = new ArrayList<>();
        List<String> tableField = fileTestMapper.getTableField(tableName);
        for( String field :tableField){
            List<String> column = new ArrayList<>();
            if (!field.equals("create_time")&&!field.equals("delete_time")&&!field.equals("update_time")&&!field.equals("id")){
                column.add(field);
                excelInfo.add(column);
            }
        }
        return excelInfo;
    }

    @Override
    public HorizontalCellStyleStrategy handlerStyleWrite() {
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 背景设置为灰色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontName("宋体");
        headWriteFont.setFontHeightInPoints((short) 13);
        headWriteCellStyle.setWriteFont(headWriteFont);
        // 内容的策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
/*        // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
        contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        // 背景绿色
        contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setFontHeightInPoints((short) 20);
        contentWriteCellStyle.setWriteFont(contentWriteFont);*/
        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    }
    @Override
    public BannerVo getById() {
      BannerVo bannerVo =  fileTestMapper.getBannerById(1);
      return bannerVo;
    }

    @Override
    public List<FileBO> upload(MultiValueMap<String, MultipartFile> fileMap) {
        List<FileBO> res = new ArrayList<>();
        // if(fileMap ==null){
        //     throw new NotFoundException("未选择文件");
        // }
        /**
         * @Description: file->{} 为实现preHandler接口 返回Boolean类型
         */
        uploader.upload(fileMap, file -> {
            String md5 =file.getMd5();
            FileDO found = fileTestMapper.selectByMd5(md5);
            // QueryWrapper<FileDO> queryWrapper = new QueryWrapper<>();
            // queryWrapper.eq("md5",file.getMd5());
            // FileDO found = fileTestMapper.selectOne(queryWrapper);
            // 数据库中不存在
            if (found == null) {
                FileDO fileDO = new FileDO();
                BeanUtil.copyProperties(file, fileDO);
                this.getBaseMapper().insert(fileDO);
                res.add(transformDoToBo(fileDO, file.getKey()));
                return true;
            }
            log.info(found.toString());
            // 已存在，则直接转化返回
            res.add(transformDoToBo(found, file.getKey()));
            log.info(res.toString());
            return false;
        });
        return res;
    }

    @Override
    public boolean checkFileExistByMd5(String md5) {
        return this.getBaseMapper().selectCountByMd5(md5) > 0;
    }

    private FileBO transformDoToBo(FileDO file, String key) {
        FileBO bo = new FileBO();
        BeanUtil.copyProperties(file, bo);
        if (file.getType().equals(FileConstant.LOCAL)) {
            String s = servePath.split("/")[0];
            bo.setUrl(domain + s + "/" + file.getPath());
        } else {
            bo.setUrl(file.getPath());
        }
        bo.setKey(key);
        return bo;
    }
}
